package com.demo.controller;

import com.demo.model.JsonMessage;
import com.demo.service.SysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Map;

@Controller
@Api(value = "CRM字典接口")
@RequestMapping("/admin/dict")
public class DictController {

    @Autowired
    private SysDictService dictService;

    @ApiOperation(value = "字典列表")
    @RequestMapping("list")
    @ResponseBody
    public JsonMessage list(@RequestParam(defaultValue = "1") int pageIndex,
                            @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        message.setData(dictService.findAll(pageIndex, pageSize));
        return message;
    }

    @ApiOperation(value = "按名字查询")
    @RequestMapping("listByGroupName")
    @ResponseBody
    public JsonMessage listByGroupName(String groupName, @RequestParam(defaultValue = "1") int pageIndex,
                                       @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        message.setData(dictService.findByGroup(groupName, pageIndex, pageSize));
        return message;
    }

    @ApiIgnore
    @RequestMapping("listByGroup")
    @ResponseBody
    public JsonMessage listByGroup(String groupName) {
        JsonMessage message = new JsonMessage();
        message.setData(dictService.findByGroupName(groupName));
        return message;
    }

    @ApiOperation(value = "查看单个信息")
    @RequestMapping("get")
    @ResponseBody
    public JsonMessage get(@RequestParam("id") Integer id) {

        JsonMessage message = new JsonMessage();
        Map<String, Object> map = new HashMap<>();
        map.put("dict", dictService.get(id));
        map.put("group", dictService.findGroup());
        message.setData(map);
        return message;
    }

    @ApiOperation(value = "删除单个信息")
    @PostMapping("remove")
    @ResponseBody
    public JsonMessage remove(Integer id) {
        JsonMessage message = new JsonMessage();
        message.setMessage("删除成功");
        if (dictService.remove(id) <= 0) {
            message.setSuccess(false);
            message.setData("删除失败!");
        }
        return message;
    }

    @ApiIgnore
    @PostMapping("group")
    @ResponseBody
    public JsonMessage findGroup() {
        JsonMessage jsonMessage = new JsonMessage();
        jsonMessage.setData(dictService.findGroup());
        return jsonMessage;
    }

}
